package net.guerlab.smart.platform.user.api.autoconfig;

import lombok.AllArgsConstructor;
import net.guerlab.smart.platform.user.api.OperationLogApi;
import net.guerlab.smart.platform.user.service.service.OperationLogHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.*;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.lang.NonNull;

/**
 * @author guer
 */
@Configuration
@Conditional(OperationLogApiLocalServiceAutoConfigure.WrapperCondition.class)
public class OperationLogApiLocalServiceAutoConfigure {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Bean
    @ConditionalOnBean(OperationLogHandler.class)
    public OperationLogApi operationLogApiLocalServiceWrapper(OperationLogHandler service) {
        return new OperationLogApiLocalServiceWrapper(service);
    }

    @SuppressWarnings("WeakerAccess")
    static class WrapperCondition implements Condition {

        @Override
        public boolean matches(@NonNull ConditionContext context, @NonNull AnnotatedTypeMetadata metadata) {
            try {
                ClassLoader classLoader = WrapperCondition.class.getClassLoader();
                return classLoader.loadClass("net.guerlab.smart.platform.user.service.service.OperationLogHandler")
                        != null;
            } catch (Exception e) {
                return false;
            }
        }
    }

    @AllArgsConstructor
    private static class OperationLogApiLocalServiceWrapper implements OperationLogApi {

        private final OperationLogHandler handler;

        @Override
        public void add(String operationContent, Long userId, Object... operationParams) {
            handler.add(operationContent, userId, operationParams);
        }
    }
}
